package org.itest.intellif.util;

import org.apache.commons.codec.binary.Base64;

import java.io.*;

/**
 * <p>Title: Base64Utils</p>
 * <p>Date: 2020/2/14 </p>
 * <p>Description: </p>
 *
 * @author sunxinhe
 */
public class Base64Utils {
    /**
     * 图片转为Base64字节码
     * @param path 图片路径
     * @return 返回base64字节码
     */
    public static String imageToBase64(String path) {
        byte[] data = null;
        try {
            InputStream in = new FileInputStream(path);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Base64 base64 = new Base64();
        return base64.encodeToString(data);
    }

    /**
     * Base64字节码转图片
     * @param base64Str 字节码存储路径
     * @param path 文件存储路径
     * @return 返回true或者false
     */
    public static boolean base64ToImage(String base64Str, String path) {
        if (base64Str == null){
            return false;
        }
        Base64 base64 = new Base64();
        try {
            byte[] bytes = base64.decodeBase64(base64Str);
            for (int i = 0; i < bytes.length; ++i) {
                if (bytes[i] < 0) {
                    bytes[i] += 256;
                }
            }
            File img = new File(path);
            if (!img.getParentFile().exists()) {
                img.getParentFile().mkdirs();
            }
            OutputStream out = new FileOutputStream(path);
            out.write(bytes);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public static void main(String[] args) {
        try {
            /**
             String base64Code =new String(encodeBase64File("D:\\test1.txt"));
             System.out.println(base64Code);
             decoderBase64File(base64Code, "D:\\2.txt");
             toFile(base64Code, "D:\\3.txt");
             **/
//            String base64Code =new String(encodeBase64File("D:\\test1.zip"));
//            System.out.println(base64Code);
//            decoderBase64File(base64Code, "D:\\2.zip");
//            toFile(base64Code, "D:\\3.txt");

            String s = imageToBase64("/data/workspace/intellif/img-my/my2020021401.jpeg");
            System.out.println(s);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void Base64Method(){
        Base64 base64 = new Base64();
        String str = base64.encodeToString("123456".getBytes());
        System.out.println(str);
        System.out.println("-----------解密----------");
        String s = new String(base64.decode(str));
        System.out.println(s);
    }


}
